const fs = require('fs');
const path = require('path');
const fsExtra = require('fs-extra');
const { omit } = require('lodash');
const { defineConfig, build } = require('vite');
const vue = require('@vitejs/plugin-vue');
const vueJsx = require('@vitejs/plugin-vue-jsx');
const dts = require('vite-plugin-dts');

const package = require('../../package.json');

const getVersion = () => {
    const versionNums = package.version.split('.');
    return versionNums.map((num, index) => (index === versionNums.length - 1 ? +num + 1 : num)).join('.');
};

const createPackageJson = async (version) => {
    package.version = getVersion(version);
    package.main = './farris.all.umd.js';
    package.module = './farris.all.esm.js';
    package.style = './style.css';
    package.dependencies = omit(package.dependencies, 'vue');
    package.types = './types/index.d.ts';
    const fileStr = JSON.stringify(omit(package, 'scripts', 'devDependencies'), null, 2);
    await fsExtra.outputFile(path.resolve('./package', `package.json`), fileStr, 'utf-8');
};

async function buildSeperately(componentName) {
    await build(
        defineConfig({
            configFile: false,
            publicDir: false,
            plugins: [vue(), vueJsx()],
            build: {
                lib: {
                    entry: `./components/${componentName}/index.ts`,
                    name: componentName,
                    fileName: 'index',
                    formats: ['esm', 'umd']
                },
                outDir: `./package/${componentName}`,
                rollupOptions: {
                    external: ['vue', '@vueuse/core', '@vue/shared', 'bignumber.js', 'lodash', 'lodash-es'],
                    output: {
                        globals: {
                            vue: 'Vue',
                            'bignumber.js': 'BigNumber'
                        }
                    }
                }
            }
        })
    );
    const packageContent = `{
    "name": "${componentName}",
    "version": "${getVersion()}",
    "main": "index.umd.js",
    "module": "index.esm.js",
    "style": "style.css",
    "types": "../types/${componentName}/index.d.ts"
}`;
    fsExtra.outputFile(`./package/${componentName}/package.json`, packageContent, 'utf-8');
}

exports.build = async () => {
    await build(
        defineConfig({
            configFile: false,
            publicDir: false,
            plugins: [
                vue(),
                vueJsx(),
                dts({
                    entryRoot: './components',
                    outputDir: `./package/types`,
                    noEmitOnError: true,
                    skipDiagnostics: true
                })
            ],
            build: {
                lib: {
                    entry: './components/index.ts',
                    name: 'FarrisVue',
                    fileName: 'farris.all',
                    formats: ['esm', 'umd']
                },
                outDir: './package',
                rollupOptions: {
                    external: ['vue', '@vueuse/core', '@vue/shared', 'bignumber.js', 'lodash', 'lodash-es'],
                    output: {
                        globals: {
                            vue: 'Vue',
                            'bignumber.js': 'BigNumber'
                        }
                    }
                }
            }
        })
    );
    await createPackageJson();
    const components = fs.readdirSync('./components').filter((name) => {
        const componentDir = path.resolve('./components', name);
        const isDir = fs.lstatSync(componentDir).isDirectory();
        return isDir && fs.readdirSync(componentDir).includes('index.ts');
    });
    // buildSeperately('accordion');
    // eslint-disable-next-line no-restricted-syntax
    for (const componentName of components) {
        buildSeperately(componentName);
    }
};
